﻿using System;
using System.Collections.Generic;
using System.Text;

using MyLibrary.ThreeLayer.DataAccess.Enum;
using MyLibrary.ThreeLayer.DataAccess.MetaData;

namespace MyLibrary.ThreeLayer.DataAccess.KeyGenerator
{
    internal interface IKeyGenerator
    {
        object GetKey(object o);
    }

    internal class GuidKeyGenerator : IKeyGenerator
    {
        public object GetKey(object o)
        {
            return Guid.NewGuid().ToString();
        }
    }

    internal class SequenceKeyGenerator : IKeyGenerator
    {
        private const int INIT_KEY_VALUE = 0x2710;

        public object GetKey(object o)
        {

        }
    }

    internal static class KeyGeneratorFactory
    {
        public static void GenerateKey(object entity, MappingCollection collection)
        {
            IList<MappingField> keyFields = collection.GetKeyFields();
            foreach (MappingField field in keyFields)
            {
                IKeyGenerator keyGenerator = GetKeyGenerator(field);
                if (keyGenerator != null)
                    field.SetValue(entity, keyGenerator.GetKey(entity));
            }
        }

        public static IKeyGenerator GetKeyGenerator(MappingField field)
        {
            if (field.IsPrimaryKey)
            {
                if (field.KeyGenerateType == PrimaryKeyType.Identity)
                    return null;
                if (field.KeyGenerateType == PrimaryKeyType.Guid)
                    return new GuidKeyGenerator();
                if (field.KeyGenerateType == PrimaryKeyType.Sequence)
                    return new SequenceKeyGenerator();
            }
        }
    }
}
